package com.lucenex.util;



import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.MultiReader;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.NIOFSDirectory;
import org.apache.lucene.store.NoLockFactory;

import com.lucenex.core.LuceneDataSource;
import com.lucenex.core.LuceneXConfig;

import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
/**
 * Lucene资源管理
 * @author zxw
 *
 */
@Builder
public class OpenLuceneSource {
	
	@Getter @Setter private String indexPath;
	
	@Getter @Setter private PerFieldAnalyzerWrapper analyzer;
	
	/**
	 * 打开写源
	 * @return
	 * @throws IOException
	 */
	public IndexWriter indexWriter() throws IOException {
		Path path = Paths.get(indexPath);
		if(!Files.isReadable(path)) {
			throw new IOException("文件目录不可读或不存在:"+indexPath);
		}
		FSDirectory dir = NIOFSDirectory.open(path, NoLockFactory.INSTANCE);
		IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);
		IndexWriter indexWriter = new IndexWriter(dir, indexWriterConfig);
		return indexWriter;
	}
	
	/**
	 * 打开读源
	 * @return
	 * @throws IOException
	 */
	public IndexSearcher indexSearcher() throws IOException {
		DirectoryReader reader = DirectoryReader.open(indexWriter()); 
		IndexSearcher indexSearcher = new IndexSearcher(reader);
		return indexSearcher;
	}
	
	/**
	 * 写源 转换到 读源
	 * @param indexWriter
	 * @return
	 * @throws IOException
	 */
	public IndexSearcher dynamicIndexSearcher(IndexWriter indexWriter) throws IOException {
		DirectoryReader reader = DirectoryReader.open(indexWriter); 
		IndexSearcher indexSearcher = new IndexSearcher(reader);
		return indexSearcher;
	}
	
	/**
	 * 多源合并 查询
	 * @param str
	 * @return
	 * @throws IOException
	 */
	public LuceneXConfig mergeSource(String[] str) throws IOException {
		int length = str.length;
		if(length > 1) {
			IndexReader[] indexReaders = new IndexReader[length];
			for (int i = 0; i < length; i++) {
				IndexWriter writer = LuceneDataSource.build().getDataSource(str[i]).getWriter();
				indexReaders[i] = DirectoryReader.open(writer);
			}
			MultiReader reader = new MultiReader(indexReaders);
			return LuceneXConfig.builder().searcher(new IndexSearcher(reader)).build();
		}
		return null;
	}
	
	
}
